package com.sprucetec.live.common.webcontext;

import com.alibaba.dubbo.rpc.Filter;
import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.Result;
import com.alibaba.dubbo.rpc.RpcException;
import com.google.common.collect.Lists;
import com.sprucetec.live.base.entity.User;
import com.sprucetec.live.constants.SprucetecConstant;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: zhangyb
 * Date: 2019/1/17
 * Time: 16:15
 * Description: 接收从controller层传递过来的当前登录用户
 **/
public class LoginServiceDubboFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        String uid = invocation.getAttachment(SprucetecConstant.DUBBO_LOGIN_USER_CODE);
        String name = invocation.getAttachment(SprucetecConstant.DUBBO_LOGIN_USER_NAME);
        String email = invocation.getAttachment(SprucetecConstant.DUBBO_LOGIN_USER_EMAIL);
        String role = invocation.getAttachment(SprucetecConstant.DUBBO_LOGIN_USER_ROLE);
        User user = new User();
        user.setUid(uid);
        user.setName(name);
        user.setEmail(email);
        List<String> roleList = Lists.newArrayList();
        roleList.add(role);
        user.setRoleList(roleList);
        LoginUserContext.setUser(user);
        try {
            return invoker.invoke(invocation);
        } finally {
            LoginUserContext.delete();
        }
    }
}
